<template>
  <div class="app-container">
    <uc-table url="admin/inInspectionLog/getInInspectionLogPage" name="巡检记录" ref="inspectionRecordTable" pageable table-border :search-form="searchForm">
      <template slot="searchForm">
        <el-form-item>
          <el-select v-model="searchForm.taskId" placeholder="请选择任务" style="width: 100%" clearable @clear="clearInput()">
            <el-option v-for="(item,index) in taskList" :key="index"  :value="item.ucId" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="enterPriseHidden">
          <el-select v-model="searchForm.enterpriseId" placeholder="请选择所属企业" style="width: 100%" clearable  @clear="clearInput()">
            <el-option v-for="(item,index) in enterpriseDominantList" :key="index"  :value="item.ucId" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" class="filter-item" @click="handleSearch()">查询</el-button>
        </el-form-item>
      </template>
      <template slot="columns">
        <el-table-column prop="taskName" label="巡检任务" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="abnormalNum" label="异常数量" align="left" :show-overflow-tooltip="true"></el-table-column>
<!--        <el-table-column prop="videoUrl" label="视频地址" align="left" :show-overflow-tooltip="true">-->
<!--          <template slot-scope="scope">-->
<!--            {{scope.row.videoUrl||"暂无地址"}}-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="inspectionTime" label="巡检开始时间" align="left" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{scope.row.inspectionTime | dateFormat}}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="巡检结束时间" align="left" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{scope.row.endTime | dateFormat}}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="200" align="left" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" :disabled="scope.row.videoUrl==null" icon="el-icon-video-play" type="primary" @click="handleVideo(scope.row)">视频</el-button>
            <el-button size="mini" :disabled="scope.row.imageList==null" icon="el-icon-picture-outline" type="success" @click="handleImage(scope.row)">图片</el-button>
            <el-button size="mini" :disabled="scope.row.videoUrl==null" icon="el-icon-download" type="warning" @click="downloadVideo(scope.row)">视频下载</el-button>
          </template>
        </el-table-column>
      </template>
    </uc-table>
    <el-dialog title="巡检视频" :visible.sync="videoDialogVisible" width="60%">
      <video :src="videoUrl"  controls="controls" autoplay width="100%" height="450px"></video>
    </el-dialog>
    <el-dialog title="巡检照片" :visible.sync="imageDialogVisible" width="60%">
        <el-row :gutter="20">
          <el-col :span="6" v-for="(item,i) in imageList" :key="i">
            <el-image
                style="width: 150px; height: 200px"
                :src="item.imgUrl"
                :preview-src-list="images"
            >
            </el-image>
          </el-col>
        </el-row>
    </el-dialog>
  </div>
</template>

<script>
import UcTable from "@/components/UcTable/index.vue";
import {getInTaskList} from "@/api/taskinfo";
import {deleteChannel, joinChannel, pullPerson} from "@/api/alirtc";
import {showVideoUser} from "@/api/user";
import {getInEnterpriseDominantList} from "../../../api/enterpriseDominant";
import {downloadVideo} from "@/utils/index";

export default {
  name: "inspectionRecordList",
  components: {UcTable},
  data(){
    return{
      searchForm:{
        taskId:this.$route.query.ucId
      },
      videoDialogVisible:false,
      videoUrl:'',
      rtcDialogVisible:false,
      deleteLoading:false,
      taskList:[],
      enterpriseDominantList:[],
      imageList:[],
      imageDialogVisible:false,
      images:[]
    }
  },
  created() {
    this.getInTaskList()
    this.getInEnterpriseDominantList();
  },
  computed:{
    enterPriseHidden(){
      let roleCode = this.$store.getters.roleCode;
      return roleCode=="ADMIN"||roleCode=="XT-ADMIN"||roleCode=="ZD-ADMIN"||roleCode=="DD-ADMIN"||roleCode=="JW-ADMIN"||roleCode=="XZ-ADMIN"||roleCode=="WB-ADMIN"
    }
  },
  methods:{
    getInEnterpriseDominantList(){
      getInEnterpriseDominantList({deleted:false}).then(res=>{
        this.enterpriseDominantList = res.data
      }).catch(error=>{
      })
    },
    handleVideo (val){
      this.videoUrl = val.videoUrl
      this.videoDialogVisible = true
    },
    handleImage (val){
      // this.imageList = [{imgUrl:"http://202.107.190.8:10162/group1/M00/00/06/wKjwSWGcwPeAHuc6ABN4Ffj1Vag762.jpg"},
      //   {imgUrl:"http://202.107.190.8:10162/group1/M00/00/07/wKjwSWGeFZCAY8kCAA74ThbuyQY296.jpg"},
      //   {imgUrl:"http://202.107.190.8:10162/group1/M00/00/06/wKjwSWGcwPeAHuc6ABN4Ffj1Vag762.jpg"},
      //   {imgUrl:"http://202.107.190.8:10162/group1/M00/00/06/wKjwSWGcwPeAHuc6ABN4Ffj1Vag762.jpg"},
      //   {imgUrl:"http://202.107.190.8:10162/group1/M00/00/06/wKjwSWGcwPeAHuc6ABN4Ffj1Vag762.jpg"},
      //   {imgUrl:"http://202.107.190.8:10162/group1/M00/00/06/wKjwSWGcwPeAHuc6ABN4Ffj1Vag762.jpg"}]
      this.imageList = val.imageList
      this.imageList.forEach(i=>{
        this.images.push(i.imgUrl)
      })
      this.imageDialogVisible = true
    },
    downloadVideo(row){
      downloadVideo(row.videoUrl,row.taskName)
    },
    clearInput(){
      this.searchForm.taskId = null
      this.handleSearch()
    },
    handleSearch(){
      this.$refs.inspectionRecordTable.getTableData(1)
    },
    handleInfo(val){
      this.$router.push("/taskManage/inspectionRecordInfo/"+val.ucId)
    },
    //校验当前设备是否支持
    isSupport(val,debug,channel){
      let option = {}
      let _this = this;
      if (debug){
        option.isDebug=true
      }
      val.isSupport(option).then((res)=>{
        this.onJoinEvent(val)
        this.onPublisher(val)
        this.onBye(val)
        this.onLeave(val)
        this.OnRefresh(val)
        this.startPreview(val)
        this.hasVideo = true;
        joinChannel({displayName:"消防队",channelId:channel.channel.substring(6),admin:false}).then(res=>{
          console.log("joinChannel")
          console.log(res.data)
          _this.aliWebrtc.joinChannel(res.data,"消防队").then(obj=>{
            _this.$nextTick(() => {
              _this.publish(_this.aliWebrtc)
              _this.startPreview(_this.aliWebrtc)
            });
            console.log("加入频道成功")
          }).catch((error)=>{
            console.log("加入频道失败",error)
          })
        }).catch(error=>{
          console.log("加入频道失败",error)
        })
      }).catch((error)=>{
        console.log("加入频道失败",error)
        this.$notify.error({
          title: '成功',
          message: "当前设备不支持webrtc"
        })
      })
    },
    //开启本地预览模式
    startPreview(val){
      val.startPreview(this.$refs.localVideo).then(()=>{
        console.log("本地预览")
      }).catch((error) => {
        console.log("预览失败",error)
      });
    },
    //推发布流
    publish(val){
      val.configLocalAudioPublish = true;
      val.configLocalCameraPublish = true;
      val.publish().then(()=>{
        console.log("发布流成功")
      } ,(error)=>{
        console.log("发布流失败",error);
      });
    },
    //加入视频通话
    joinChannel(val){
      this.aliWebrtc = new AliRtcEngine();
      this.isSupport(this.aliWebrtc,true,val)
    },
    // remote用户加入房间 onJoin
    onJoinEvent(val){
      val.on("onJoin", (publisher) => {
        console.log(publisher)
        val.configRemoteAudio(publisher.userId, true);
        val.configRemoteCameraTrack(publisher.userId, true, true);
        // showAlert(publisher.displayName + "加入房间","success");
        console.log(publisher.displayName + "加入房间");
      });
    },
    //remote流发布事件 onPublish
    onPublisher(val){
      val.on("onPublisher", (publisher) => {
        val.subscribe(publisher.userId).then((userId)=>{
          console.log("userId")
          console.log(userId)
          console.log(this.remoteList)
          console.log(this.$refs["remoteVideo"+(this.remoteList.length-1)])
          this.$nextTick(() => {
            val.setDisplayRemoteVideo(userId,this.$refs["remoteVideo"+(this.remoteList.length-1)],1)
          });
        },(error)=>{
          console.log(error.message);
        });
        let index = this.remoteList.indexOf(publisher);
        console.log(index)
        if (index === -1&&this.remoteList.length<8) {
          //新增
          this.remoteList.push(publisher)

        }
      });
    },
    //remote流结束发布事件 onUnPublisher
    onUnPublisher(val){
      val.on("onUnPublisher", (publisher) => {
        console.log("onUnPublisher",publisher);
        let index = this.remoteList.findIndex(function(item) {
          return item.userId === publisher.userId;
        });
        console.log("index")
        console.log(index)
        this.remoteList.splice(index,1)
        if (this.remoteList.length<1){
          this.leaveVideo()
        }
      });
    },
    // 被服务器踢出或者频道关闭时回调 onBye
    onBye(val){
      val.on("onBye",(message) =>{
        var msg;
        switch (message.code) {
          case 1:
            msg = "被服务器踢出";
            break;
          case 2:
            msg = "频道关闭";
            break;
          case 3:
            msg = "同一个ID在其他端登录,被服务器踢出";
            break;
          default:
            msg = "onBye";
        }
        this.remoteList = []
      });
    },
    leaveVideo(){
      this.remoteList =[]
      this.aliWebrtc.leaveChannel();
      this.aliWebrtc.dispose();
      this.hasVideo = false;
    },
    /**
     * 检测到用户离开频道
     * 更新用户列表
     * 移除用户视图
     */
    onLeave(val){
      val.on("onLeave", (publisher) => {
        console.log(publisher);
        let index = this.remoteList.findIndex(function(item) {
          return item.userId === publisher.userId;
        });
        console.log(index)
        this.remoteList.splice(index,1)
        if (this.remoteList.length<1){
          this.leaveVideo()
        }
      })
    },
    //页面刷新时调用
    OnRefresh(val){
      window.onbeforeunload=function (e) {
        if (!val){
          console.log("isSupport失败");
          return ;
        }
        val.leaveChannel();
        val.dispose();
      }
    },
    beforeunloadHandler(){
      this.beforeUnloadTime=new Date().getTime();
    },
    unloadHandler(e){
      this.gapTime=new Date().getTime()-this.beforeUnloadTime;
      //判断是窗口关闭还是刷新
      if(this.gapTime<=5){//浏览器关闭
        //自己的操作行为
        let  actions = {"type":"offline","ucId":sessionStorage.getItem('ucId')};
        this.webSocketSend(JSON.stringify(actions));
        this.webSock.close() //离开路由之后断开websocket连接
      }
    },
    showVideoUser(){
      showVideoUser({customize:this.userId}).then(res=>{
        this.userList = res.data
      })
    },
    pullVideo(){
      this.videoForm.channelId = this.userId
      pullPerson(this.videoForm).then(res=>{
        console.log(res)
        this.videoForm = {}
        this.pullVideoStatus = false
      })
    },
    deleteChannel(){
      this.deleteForm.channelId = this.userId
      deleteChannel(this.deleteForm).then(res=>{
        console.log(res)
        this.deleteForm.channelId = {}
        this.resizeBox = false
        // this.unPublish(this.aliWebrtc)
        // this.stopPreview(this.aliWebrtc)
      })
    },
    unPublish(val){
      val.unPublish().then(()=>{
        console.log("结束流成功")
      } ,(error)=>{
        console.log("结束流失败",error);
      });
    },
    stopPreview(val){
      val.stopPreview().then(()=>{
        console.log("结束预览成功")
      }).catch((error) => {
        console.log("结束预览失败")
        // 结束预览失败
      });
    },
    getInTaskList(){
      getInTaskList({}).then(res=>{
        this.taskList = res.data
      }).catch(error=>{

      })
    },

  }
}
</script>
